angular.module('loadingStatus', []).config(function($httpProvider) {
	$httpProvider.interceptors.push('loadingStatusInterceptor');
}).directive('loadingStatusMessage', function() {
	return {
		link : function($scope, $element, attrs) {
			var show = function() {
				$element.css('display', 'block');
			};
			var hide = function() {
				$element.css('display', 'none');
			};
			$scope.$on('loadingStatusActive', show);
			$scope.$on('loadingStatusInactive', hide);
			hide();
		}
	};
}).factory('loadingStatusInterceptor', function($q, $rootScope) {
	var activeRequests = 0;
	var started = function() {
		if (activeRequests == 0) {
			$rootScope.$broadcast('loadingStatusActive');
		}
		activeRequests++;
	};
	var ended = function() {
		activeRequests--;
		if (activeRequests == 0) {
			$rootScope.$broadcast('loadingStatusInactive');
		}
	};
	return {
		request : function(config) {
			started();
			return config || $q.when(config);
		},
		response : function(response) {
			ended();
			return response || $q.when(response);
		},
		responseError : function(rejection) {
			ended();
			return $q.reject(rejection);
		}
	};
});

var api = angular.module('infoApi', [ 'ngResource' ]);
api.factory("BNR", function($resource) {
	return $resource('/api/bnr.action', {}, {
		query : {
			method : 'GET',
			isArray : false,
			transformResponse : function(data, headers) {
				var data = angular.fromJson(data), responsedata = {
					data : [],
					parsingDate : data.reader.parsingDate
				};
				for (var i = 1; i < data.currencyMap.length; i++) {
					var el = data.currencyMap[i];
					responsedata.data.push({
						multiplier : el.multiplier,
						currencyCode : el.currency,
						currencyDescr : el.currencyDescr,
						bid : el.bid,
						baseCurrency : data.reader.seller.baseCurrency
					});
				}
				return responsedata;
			}
		}
	});
});
api.factory("BCE", function($resource) {
	return $resource('/api/bce.action', {}, {
		query : {
			method : 'GET',
			isArray : false,
			transformResponse : function(data, headers) {
				var data = angular.fromJson(data), responsedata = {
					data : [],
					parsingDate : data.reader.parsingDate
				};
				for (var i = 1; i < data.currencyMap.length; i++) {
					var el = data.currencyMap[i];
					responsedata.data.push({
						multiplier : el.multiplier,
						currencyCode : el.currency,
						currencyDescr : el.currencyDescr,
						bid : el.bid,
						baseCurrency : data.reader.seller.baseCurrency
					});
				}
				return responsedata;
			}
		}
	});
});
api.factory("ROCOMPARE", function($resource) {
	return $resource('/api/rocompare.action', {}, {
		query : {
			method : 'GET',
			isArray : false,
			transformResponse : function(data, headers) {
				var responsedata = [], data = angular.fromJson(data);
				return angular.fromJson(data);
			}
		}
	});
});
google.load('visualization', '1', {
	packages : [ 'corechart' ]
});
google.setOnLoadCallback(function() {
	angular.bootstrap(document.body, [ 'infoValuta' ]);
});

var app = angular.module('infoValuta', [ 'ui.bootstrap', 'loadingStatus', 'ngResource', 'infoApi', 'ngGrid', 'ngRoute' ]);
app.config([ '$routeProvider', function($routeProvider) {
	$routeProvider.when('/cursBnr', {
		templateUrl : 'templates/bnr.html',
		controller : 'BNRController'
	}).when('/cursBce', {
		templateUrl : 'templates/bce.html',
		controller : 'BCEController'
	}).when('/roCompare', {
		templateUrl : 'templates/rocompare.html',
		controller : 'ROCOMPAREController'
	}).when('/api', {
		templateUrl : 'templates/api.html'
	}).otherwise({
		redirectTo : '/api'
	});
} ]);
app.value('COMMON', {
	columnDefs : [ {
		field : "multiplier",
		displayName : "Suma"
	}, {
		field : "currencyCode",
		displayName : "Simbol",
		cellTemplate : '<span class="pull-left flagico {{row.entity[col.field]}}"></span>&nbsp;&nbsp;<span>{{row.entity[col.field]}}</span>'
	}, {
		field : "currencyDescr",
		displayName : "Moneda"
	}, {
		field : "bid",
		displayName : "Suma RON"
	}, {
		field : "baseCurrency",
		displayName : ""
	} ]

});
app.controller('BNRController', [ '$scope', 'BNR', 'COMMON', function($scope, svc, COMMON, $routeParams) {
	svc.query().$promise.then(function(resp) {
		$scope.bnrData = resp.data;
		$scope.parsingDate = resp.parsingDate;
	}, function() {
		// TODO:Handle Error
	});
	$scope.gridOptions = {
		data : 'bnrData',
		columnDefs : COMMON.columnDefs
	};

} ]);

app.controller('BCEController', [ '$scope', 'BCE', 'COMMON', function($scope, svc, COMMON, $routeParams) {
	svc.query().$promise.then(function(resp) {
		$scope.bceData = resp.data;
		$scope.parsingDate = resp.parsingDate;
	}, function() {
		// TODO:Handle Error
	});
	$scope.gridOptions = {
		data : 'bceData',
		columnDefs : COMMON.columnDefs
	};
} ]);

app.controller('MainCtrl', [ '$scope', function($scope) {
	$scope.isCollapsed = false;
	
} ]);
app.controller('ROCOMPAREController', [ '$scope', 'ROCOMPARE', function($scope, svc, $routeParams) {
	$scope.currencies = [];
	$scope.currency = {
		name : 'EUR',
		description : 'Euro'
	};

	$scope.gridOptions = {
		data : 'roCompareData',
		columnDefs : [ {
			field : "sellerName",
			displayName : "Banca ",
			cellTemplate : '<span class="pull-left bankLogo {{row.entity[col.field]}}"></span><span>{{row.entity[col.field]}}</span>'
		}, {
			field : "multiplier",
			displayName : "Suma"
		}, {
			field : "ask",
			displayName : "Vanzare"
		}, {
			field : "askDiff",
			displayName : "Bnr +/-",
			cellTemplate : '<span class="redText">{{row.entity[col.field]}}</span>'
		}, {
			field : "bid",
			displayName : "Cumparare"
		}, {
			field : "bidDiff",
			displayName : "Bnr +/-",
			cellTemplate : '<span class="redText">{{row.entity[col.field]}}</span>'
		}, {
			field : "bnr",
			displayName : "Curs bnr",
			cellTemplate : '<span class="greenText">{{row.entity[col.field]}}</span>'
		} ]

	};

	svc.query().$promise.then(function(data) {
		$scope.currencies = data.response.currencies;
		$scope.entries = data.response.entries;
		$scope.getCurrencyData({
			name : 'EUR',
			description : 'Euro'
		});
	}, function() {
	});

	$scope.drawCharts = function(chartDataV, chartDataC) {
		var chartOptionsV = {
			title : 'Vanzare',
			
			legend : {
				position : "none"
			},
			backgroundColor : '#f5f5f5'
		};
		var chartOptionsC = {
			title : 'Cumparare',
			
			legend : {
				position : "none"
			},
			backgroundColor : '#f5f5f5'
		};
		chartVanzare = new google.visualization.ColumnChart(document.getElementById('chartv'));
		chartVanzare.draw(google.visualization.arrayToDataTable(chartDataV), chartOptionsV);
		chartCumparare = new google.visualization.ColumnChart(document.getElementById('chartc'));
		chartCumparare.draw(google.visualization.arrayToDataTable(chartDataC), chartOptionsC);

	}

	$scope.getCurrencyData = function(currency) {
		$scope.roCompareData = [];
		var bnrBid, bnrMultiplier, chartDataV = [ [ 'Banca', 'Vanzare' ] ], chartDataC = [ [ 'Banca', 'Cumparare' ] ];
		$scope.roCompareData = [];
		angular.forEach($scope.entries, function(value, key) {
			angular.forEach(value, function(v, k) {
				$scope.$broadcast('loadingStatusActive');
				if (v.currency == currency.name) {
					if (v.seller.name == 'BNR') {
						bnrBid = v.bid;
						bnrMultiplier = v.multiplier;
						$scope.parsingDate = v.parsingDate;
					} else {
						$scope.roCompareData.push({
							sellerName : v.seller.name,
							multiplier : v.multiplier + " " + currency.name,
							ask : v.ask + ' ' + v.seller.baseCurrency,
							askDiff : (v.ask - bnrBid).toFixed(6),
							bid : v.bid + ' ' + v.seller.baseCurrency,
							bidDiff : (v.bid - bnrBid).toFixed(6),
							bnr : bnrBid
						});
						chartDataV.push([ v.seller.name, v.ask ]);
						chartDataC.push([ v.seller.name, v.bid ])
					}
				}
			});
		});
		$scope.drawCharts(chartDataV, chartDataC);
		$scope.$broadcast('loadingStatusInactive');
	};
} ]);